package com.icefish.control;

import com.alibaba.fastjson.JSONObject;
import com.icefish.bean.Order;
import com.icefish.bean.fastjsonParse.Meta;
import com.icefish.bean.fastjsonParse.getOrderByUserID.GetOrderByUserIDResp;
import com.icefish.dao.OrderDao;
import com.icefish.daoFactory.DaoFactory;
import com.icefish.utils.Init_Req_Resp_Config;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.util.ArrayList;

@WebServlet("/getOrdersByUserID")
public class getOrdersByUserID extends HttpServlet {

    private OrderDao orderDao = DaoFactory.getOrderDaoInstance();
    protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {

        // 标准配置
        Init_Req_Resp_Config.init(request, response);
        //从域中获取用户id
        Integer userId = Integer.valueOf(request.getParameter("user_id"));

        GetOrderByUserIDResp getOrderByUserIDResp = new GetOrderByUserIDResp();
        Boolean flag = null;

        try {
            //根据用户id获取订单信息
            ArrayList<Order> orders=orderDao.selectOrderByUserId(userId);
            //将查询到的信息赋值给getOrderByUserIDResp
            getOrderByUserIDResp.setData(orders);

            //判断数据是否获取正常
            if(getOrderByUserIDResp.getData()!=null){

                flag=true;
            }

        } catch (Exception e) {
            e.printStackTrace();
        }

        if (flag==true){
            Meta meta = new Meta("获取商品信息成功",200);
            getOrderByUserIDResp.setMeta(meta);
        }
        else {
            Meta meta = new Meta("获取商品信息失败", 200);
            getOrderByUserIDResp.setMeta(meta);
        }

        //相应Json数据
        JSONObject jsonObject = new JSONObject();
        // 转换成json
        String backToBrowser = jsonObject.toJSONString(getOrderByUserIDResp);

        // 响应数据
        response.getWriter().write(backToBrowser);


    }

    protected void doGet(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        this.doPost(request, response);
    }
}
